﻿// recvfrom_client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <stdio.h>

#include <winsock.h>
#pragma comment(lib,"ws2_32.lib")

int main()
{
    //0.确定协议版本信息；
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (2 != LOBYTE(wsaData.wVersion) ||
        2 != HIBYTE(wsaData.wVersion))
    {
        printf("确定协议版本信息失败%d\n", GetLastError());
        return -1;
    }
    printf("确定协议版本信息成功\n");


    //1.创建socket
    SOCKET clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (SOCKET_ERROR == clientSocket)
    {
        printf("创建socket失败:%d\n", GetLastError());

        //5.清理协议版本信息：
        WSACleanup();


        return -1;
    }
    printf("创建socket成功\n");


    //2.确定服务器的协议地址族：
    SOCKADDR_IN sAddr = { 0 };
    sAddr.sin_family = AF_INET;
    sAddr.sin_addr.S_un.S_addr = inet_addr("10.133.98.104");
    sAddr.sin_port = htons(6666);


    //3通信
    char buff[256];
    char temp[256] = { 0 };
    int r,ret;
    while (1)
    {
        printf("请输入:>");
        scanf("%s", buff);

        r = sendto(clientSocket, buff, strlen(buff), NULL, (sockaddr*)&sAddr, sizeof(sAddr));
        if (r > 0)
        {
            printf("发送%d 数据到服务器\n", r);
            ret = recv(clientSocket, temp, strlen(temp), NULL);
            if (ret > 0)
            {
                temp[ret] = 0;
                printf("ret:%d  %s\n", ret,temp);
            }
            

        }

        

    }


    //4.关闭socket
    closesocket(clientSocket);


    //5.清理协议版本信息：
    WSACleanup();

    return 0;
}
